#
# Copyright (C) 2009-2010 GSyC/LibreSoft, Universidad Rey Juan Carlos
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
# 
#    Author : Jose Gato Luis <jgato@libresoft.es>
#

from libs.channel11870.Channel11870 import Channel11870
from libs.channelPanoramio.ChannelPanoramio import ChannelPanoramio
from libs.channelYoutube.ChannelYoutube import ChannelYoutube
from social.layers.InternalLayer import InternalLayer
from settings import BASEDIR 

from os import path 

CHANNELS_SUPPORTED= { "11870" : "Channel11870(\"\")",
                      "panoramio" : "ChannelPanoramio(\"\")",
                      "youtube" : "ChannelYoutube(\"\")"}

ICONS_PATH = path.join(BASEDIR, "social", "site_media", "layers", "icons")

def layers_request(layer_id, search, options):
    
    if layer_id in CHANNELS_SUPPORTED:
        channel = eval(CHANNELS_SUPPORTED[layer_id]   )
   
        success, result = channel.set_options(options)
        if success:
            channel.set_search_pattern(search)
            success, nodesList = channel.process()
            return success, nodesList
        else:
            return success, result
    elif layer_id == "lgs":

        lgs = InternalLayer()

        success, result = lgs.set_options(options)
        if success:
            lgs.set_search_pattern(search)
            success, nodesList = lgs.process()
            return success, nodesList
        else:
            return success, result
        
    else:
        return False, "Channel not supported"
    
         
def layers_info(layer_id):
    if layer_id in CHANNELS_SUPPORTED:
        channel = eval(CHANNELS_SUPPORTED[layer_id]   )
        return True, channel.get_info()

    elif layer_id == "lgs":
        lgs = InternalLayer()
        return True, lgs.get_info() 
    else:
        return False, "Channel not supported"   


def layers_icon(layer_id):
    
    try:
        url = path.join( ICONS_PATH , layer_id + ".png")
        image_data = open(url, "rb").read()
        return True, image_data 
    except ValueError:
        return False, "Error retrieving icon"